package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func setupRouter() *gin.Engine {
	r := gin.Default()
	r.GET("/test", func(context *gin.Context) {
		context.String(200, "pong")
	})
	r.GET("/ping", func(context *gin.Context) {
		context.JSON(http.StatusOK, gin.H{
			"message": "pong",
		})
	})
	return r
}
func main() {
	r := setupRouter()
	loadHtmlTemplate(r)
	//加载一个html模板文件
	//r.LoadHTMLFiles("./index.html")
	buildMappingHtml(r)
	buildRestFulApi(r)

	r.Run()
}
func buildMappingHtml(r *gin.Engine) {
	r.GET("posts/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "posts/index.html", gin.H{
			"title": "Post",
		})
	})
	r.GET("users/index", func(c *gin.Context) {
		c.HTML(http.StatusOK, "users/index.html",
			gin.H{
				"title": "User",
			})
	})
}

func loadHtmlTemplate(r *gin.Engine) {
	//加载templates下的所有文件作为模板
	r.LoadHTMLGlob("templates/**/*")
}

// gin restful api example
func buildRestFulApi(r *gin.Engine) {
	r.GET("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"operation": "get book"})
	})
	r.POST("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"operation": "add book"})
	})
	r.PUT("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"operation": "update book"})
	})
	r.DELETE("/book", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"operation": "delete book"})
	})
}
